package com.example.mydy;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import com.example.mydy.api.ApiClient;
import com.example.mydy.api.UserApi;
import com.example.mydy.utils.NetworkUtils;
import com.example.mydy.utils.SharedPreferencesManager;
import com.example.mydy.RewardManagementActivity;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class AdminActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "AdminActivity";
    private static final String PREFS_NAME = "MyAppPrefs";
    private static final String KEY_TOKEN = "token";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_USER_ID = "userId";
    private static final String KEY_USER_TYPE = "userType";
    private static final String KEY_USER_NICKNAME = "userNickname";
    private static final String KEY_IS_LOGGED_IN = "isLoggedIn";

    private CardView userManagementCard;
    private CardView announcementManagementCard;
    private CardView advertisementManagementCard;
    private CardView projectManagementCard;
    private CardView rewardManagementCard;
    private CardView taskRewardCard;
    private CardView simulationManagementCard;
    private CardView withdrawalManagementCard;
    private TextView adminNameText;

    private SharedPreferences prefs;
    
    // 改为实例变量
    private boolean isNavigating = false;
    
    private UserApi userApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin);

        Log.d(TAG, "onCreate: AdminActivity创建");
        prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        
        // 初始化 Retrofit 和 UserApi
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiClient.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        userApi = retrofit.create(UserApi.class);

        // 检查管理员权限
        checkAdminAccess();

        // 初始化视图
        initViews();
        
        // 设置管理员名称
        String adminName = prefs.getString(KEY_USER_NICKNAME, prefs.getString(KEY_USERNAME, "管理员"));
        adminNameText.setText("管理员: " + adminName);
        
        // 设置点击监听器
        setupClickListeners();
        
        // 加载管理员信息
        loadAdminInfo();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: AdminActivity销毁");
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if (!checkAdminAccess()) {
            Log.w(TAG, "onResume: 检测到非管理员用户");
            Toast.makeText(this, "您没有管理员权限", Toast.LENGTH_SHORT).show();
            navigateToLogin();
        }
    }

    private boolean checkAdminAccess() {
        boolean isLoggedIn = prefs.getBoolean(KEY_IS_LOGGED_IN, false);
        String token = prefs.getString(KEY_TOKEN, "");
        String userType = prefs.getString(KEY_USER_TYPE, "");
        
        Log.d(TAG, "检查管理员访问权限: isLoggedIn=" + isLoggedIn + ", token有效=" + (token != null && !token.isEmpty()) + ", userType=" + userType);
        
        // 在线模式下的验证逻辑
        // 检查是否登录、令牌有效，以及是否为管理员
        if (!isLoggedIn || token == null || token.isEmpty()) {
            Log.d(TAG, "未登录或令牌为空");
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            navigateToLogin();
            return false;
        }
        
        boolean isAdmin = "admin".equalsIgnoreCase(userType);
        Log.d(TAG, "检查管理员权限: " + isAdmin + ", userType: " + userType);
        if (!isAdmin) {
            Toast.makeText(this, "您没有管理员权限", Toast.LENGTH_SHORT).show();
            finish();
        }
        return true;
    }

    private void initViews() {
        userManagementCard = findViewById(R.id.userManagementCard);
        announcementManagementCard = findViewById(R.id.announcementManagementCard);
        advertisementManagementCard = findViewById(R.id.advertisementManagementCard);
        projectManagementCard = findViewById(R.id.projectManagementCard);
        rewardManagementCard = findViewById(R.id.rewardManagementCard);
        taskRewardCard = findViewById(R.id.taskRewardCard);
        simulationManagementCard = findViewById(R.id.simulationManagementCard);
        withdrawalManagementCard = findViewById(R.id.withdrawalManagementCard);
        adminNameText = findViewById(R.id.adminNameText);
    }

    private void setupClickListeners() {
        userManagementCard.setOnClickListener(this);
        announcementManagementCard.setOnClickListener(this);
        advertisementManagementCard.setOnClickListener(this);
        projectManagementCard.setOnClickListener(this);
        rewardManagementCard.setOnClickListener(this);
        taskRewardCard.setOnClickListener(this);
        simulationManagementCard.setOnClickListener(this);
        withdrawalManagementCard.setOnClickListener(this);
        
        // 添加任务审核入口点击监听
        findViewById(R.id.taskManagementCard).setOnClickListener(this);
        
        // 添加退出登录按钮监听
        findViewById(R.id.btn_admin_logout).setOnClickListener(this);
    }

    private void loadAdminInfo() {
        // 直接从SharedPreferences获取管理员信息
        String adminName = prefs.getString(KEY_USER_NICKNAME, prefs.getString(KEY_USERNAME, "管理员"));
        adminNameText.setText("管理员：" + adminName);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.userManagementCard) {
            navigateToUserManagement();
        } else if (id == R.id.announcementManagementCard) {
            navigateToAnnouncementManagement();
        } else if (id == R.id.advertisementManagementCard) {
            navigateToAdvertisementManagement();
        } else if (id == R.id.projectManagementCard) {
            navigateToProjectManagement();
        } else if (id == R.id.rewardManagementCard) {
            navigateToRewardManagement();
        } else if (id == R.id.taskRewardCard) {
            navigateToTaskReward();
        } else if (id == R.id.taskManagementCard) {
            navigateToTaskManagement();
        } else if (id == R.id.simulationManagementCard) {
            navigateToSimulationManagement();
        } else if (id == R.id.withdrawalManagementCard) {
            navigateToWithdrawalManagement();
        } else if (id == R.id.btn_admin_logout) {
            logout();
        }
    }

    private void navigateToUserManagement() {
        if (isNavigating) {
            Log.d(TAG, "已经在导航中，避免重复调用");
            return;
        }
        isNavigating = true;
        Intent intent = new Intent(AdminActivity.this, UserManagementActivity.class);
        startActivity(intent);
        isNavigating = false;
    }

    private void navigateToAnnouncementManagement() {
        if (isNavigating) {
            Log.d(TAG, "已经在导航中，避免重复调用");
            return;
        }
        isNavigating = true;
        try {
            Intent intent = new Intent(AdminActivity.this, AnnouncementActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "无法启动AnnouncementActivity", e);
            Toast.makeText(this, "功能开发中，即将上线", Toast.LENGTH_SHORT).show();
        }
        isNavigating = false;
    }

    private void navigateToAdvertisementManagement() {
        if (isNavigating) {
            Log.d(TAG, "已经在导航中，避免重复调用");
            return;
        }
        isNavigating = true;
        try {
            Intent intent = new Intent(AdminActivity.this, AdvertisementManagementActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "无法启动AdvertisementManagementActivity", e);
            Toast.makeText(this, "功能开发中，即将上线", Toast.LENGTH_SHORT).show();
        }
        isNavigating = false;
    }

    private void navigateToProjectManagement() {
        if (isNavigating) {
            Log.d(TAG, "已经在导航中，避免重复调用");
            return;
        }
        isNavigating = true;
        try {
            Intent intent = new Intent(AdminActivity.this, ProjectManagementActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "无法启动ProjectManagementActivity", e);
            Toast.makeText(this, "项目管理功能开发中，即将上线", Toast.LENGTH_SHORT).show();
        }
        isNavigating = false;
    }

    private void navigateToRewardManagement() {
        if (isNavigating) {
            Log.d(TAG, "已经在导航中，避免重复调用");
            return;
        }
        isNavigating = true;
        try {
            Intent intent = new Intent(AdminActivity.this, RewardManagementActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "无法启动RewardManagementActivity", e);
            Toast.makeText(this, "悬赏管理功能开发中，即将上线", Toast.LENGTH_SHORT).show();
        }
        isNavigating = false;
    }

    private void navigateToTaskReward() {
        if (isNavigating) {
            Log.d(TAG, "已经在导航中，避免重复调用");
            return;
        }
        isNavigating = true;
        try {
            Intent intent = new Intent(AdminActivity.this, TaskRewardManagement.class);
            startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "无法启动TaskRewardManagement", e);
            Toast.makeText(this, "奖励任务管理功能开发中，即将上线", Toast.LENGTH_SHORT).show();
        }
        isNavigating = false;
    }

    private void navigateToTaskManagement() {
        if (isNavigating) {
            Log.d(TAG, "已经在导航中，避免重复调用");
            return;
        }
        isNavigating = true;
        try {
            Intent intent = new Intent(AdminActivity.this, TaskManagementActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "无法启动TaskManagementActivity", e);
            Toast.makeText(this, "功能开发中，即将上线", Toast.LENGTH_SHORT).show();
        }
        isNavigating = false;
    }

    private void navigateToSimulationManagement() {
        if (isNavigating) {
            Log.d(TAG, "已经在导航中，避免重复调用");
            return;
        }
        isNavigating = true;
        try {
            Intent intent = new Intent(AdminActivity.this, SimulationManagementActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "无法启动SimulationManagementActivity", e);
            Toast.makeText(this, "功能开发中，即将上线", Toast.LENGTH_SHORT).show();
        }
        isNavigating = false;
    }

    private void navigateToWithdrawalManagement() {
        if (isNavigating) {
            Log.d(TAG, "已经在导航中，避免重复调用");
            return;
        }
        isNavigating = true;
        try {
            Intent intent = new Intent(AdminActivity.this, WithdrawalManagementActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "无法启动WithdrawalManagementActivity", e);
            Toast.makeText(this, "正在加载提现管理模块", Toast.LENGTH_SHORT).show();
        }
        isNavigating = false;
    }

    private void navigateToLogin() {
        // 防止重复导航
        if (isNavigating) {
            Log.d(TAG, "已经在导航中，避免重复调用");
            return;
        }
        
        isNavigating = true;
        Log.d(TAG, "正在跳转到登录页面");
        
        // 清除登录状态
        clearLoginInfo();
        
        Intent intent = new Intent(AdminActivity.this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
        
        // 重置导航标志，但在此活动中不会生效，因为活动已结束
        isNavigating = false;
    }
    
    private void clearLoginInfo() {
        // 清除登录状态
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(KEY_IS_LOGGED_IN, false);
        editor.putString(KEY_TOKEN, "");
        editor.putString(KEY_USER_TYPE, "");
        boolean success = editor.commit();
        
        Log.d(TAG, "清除登录信息 成功: " + success);
        NetworkUtils.clearAuthToken(this);
    }

    private void logout() {
        // 清除登录状态
        clearLoginInfo();
        
        // 跳转到登录页面
        navigateToLogin();
    }
    
    @Override
    public void onBackPressed() {
        // 不直接调用super.onBackPressed()，防止返回到其他页面造成循环问题
        // 而是回到桌面
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}